package com.lanou.connotationjoke.activity;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.lanou.connotationjoke.R;
import com.lanou.connotationjoke.adapter.LoginPagerAdapter;
import com.lanou.connotationjoke.entity.LoginUserEty;
import com.lanou.connotationjoke.fragment.DiscoveryFragment;
import com.lanou.connotationjoke.fragment.HomeFragment;
import com.lanou.connotationjoke.fragment.LoginCollectFragment;
import com.lanou.connotationjoke.fragment.LoginCommentFragment;
import com.lanou.connotationjoke.fragment.LoginContributeFragment;
import com.lanou.connotationjoke.fragment.ReviewFragment;
import com.lanou.connotationjoke.tool.MyAppllication;
import com.lanou.connotationjoke.tool.ShareSingleton;
import com.lanou.connotationjoke.tool.VolleySingleton;
import com.mob.tools.utils.UIHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import de.greenrobot.event.EventBus;


/**
 * Created by dllo on 16/1/21.
 */
public class LoginActivity extends BaseActivity implements PlatformActionListener, Handler.Callback, View.OnClickListener {
    private TabHost tabHost;
    private ImageView backIv;
    private TextView loginIntroTV;
    private ImageView setIv;
    private NetworkImageView loginIv;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR= 4;
    private static final int MSG_AUTH_COMPLETE = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //初始化SharedPreference用来存储用户数据
        sharedPreferences = getSharedPreferences("userData",MODE_PRIVATE);
        editor = sharedPreferences.edit();
        //
        backIv = (ImageView) findViewById(R.id.iv_login_back);
        setIv = (ImageView) findViewById(R.id.iv_login_set);
        loginIv = (NetworkImageView) findViewById(R.id.iv_login_icon);
        loginIntroTV = (TextView) findViewById(R.id.tv_login_intro);
        backIv.setOnClickListener(this);
        setIv.setOnClickListener(this);
        loginIv.setOnClickListener(this);
        loginIntroTV.setOnClickListener(this);
        loginIv.setDefaultImageResId(R.mipmap.my_defalut_avatar);
        loginIv.setErrorImageResId(R.mipmap.my_defalut_avatar);
        String nickName = sharedPreferences.getString("nickname", "立即登录");
        String iconUrl = sharedPreferences.getString("icon","");
        loginIntroTV.setText(nickName);
        loginIv.setImageUrl(iconUrl,VolleySingleton.getImageLoader());


        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("tab_contribute")
                .setIndicator(getLayoutInflater().inflate(R.layout.tab_contribute, null))
                .setContent(R.id.tab_contribute));
        tabHost.addTab(tabHost.newTabSpec("tab_collect")
                .setIndicator(getLayoutInflater().inflate(R.layout.tab_collect, null))
                .setContent(R.id.tab_collect));
        tabHost.addTab(tabHost.newTabSpec("tab_comment")
                .setIndicator(getLayoutInflater().inflate(R.layout.tab_comment, null))
                .setContent(R.id.tab_comment));
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.tab_contribute, new LoginContributeFragment());
        transaction.replace(R.id.tab_collect, new LoginCollectFragment());
        transaction.replace(R.id.tab_comment, new LoginCommentFragment());
        transaction.commit();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    //loginActivity的点击事件
    @Override
    public void onClick(View v) {
     switch (v.getId()){
         case R.id.iv_login_back:
             onBackPressed();
             break;
         case R.id.iv_login_set:
          ShareSingleton.getInstance().shareOnQQ("分享标题--Title","http://mob.com","分享测试文--Text",
                  "http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
             break;
         case R.id.iv_login_icon:
         boolean isLogin = sharedPreferences.getBoolean("isLogin",false);
             if (isLogin){
                 Intent intent1 = new Intent(LoginActivity.this,UserDataActivity.class);
                 startActivity(intent1);
                 finish();
             }
             break;
         case R.id.tv_login_intro:
             authorize(new QQ(this));
             break;

     }
    }

    private void authorize(Platform plat) {
        if(plat.isValid()) {
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
                login(plat.getName(), userId, null);
                return;
            }
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(false);
        plat.showUser(null);

    }





    public void onComplete(Platform platform, int action,
                           HashMap<String, Object> res) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this);
            login(platform.getName(), platform.getDb().getUserId(), res);
        }

    }

    public void onError(Platform platform, int action, Throwable t) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this);
        }
        t.printStackTrace();
    }

    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
        }
    }

    private void login(String plat, String userId, HashMap<String, Object> userInfo) {
        Message msg = new Message();
        msg.what = MSG_LOGIN;
        msg.obj = plat;
        UIHandler.sendMessage(msg, this);
    }

    public boolean handleMessage(Message msg) {
        switch(msg.what) {
            case MSG_USERID_FOUND: {
                Toast.makeText(this, R.string.userid_found, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_LOGIN: {

                String text = getString(R.string.logining, msg.obj);
                Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
                System.out.println("---------------");

//				Builder builder = new Builder(this);
//				builder.setTitle(R.string.if_register_needed);
//				builder.setMessage(R.string.after_auth);
//				builder.setPositiveButton(R.string.ok, null);
//				builder.create().show();
            }
            break;
            case MSG_AUTH_CANCEL: {
                Toast.makeText(this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
                System.out.println("-------MSG_AUTH_CANCEL--------");
            }
            break;
            case MSG_AUTH_ERROR: {
                Toast.makeText(this,R.string.auth_error, Toast.LENGTH_SHORT).show();
                System.out.println("-------MSG_AUTH_ERROR--------");
            }
            break;
            case MSG_AUTH_COMPLETE: {
                Toast.makeText(this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
                Platform qq = ShareSDK.getPlatform(this, QQ.NAME);
                String accessToken = qq.getDb().getToken(); // 获取授权token
                String openId = qq.getDb().getUserId(); // 获取用户在此平台的ID
                String nickName = qq.getDb().get("nickname");
                String url = qq.getDb().get("icon");

                editor.putString("nickname", nickName);
                editor.putString("icon", url);
                editor.putBoolean("isLogin", true);
                editor.commit();

                loginIntroTV.setText(nickName);
                loginIv.setImageUrl(url, VolleySingleton.getImageLoader());

                LoginUserEty loginUserEty = new LoginUserEty();
                loginUserEty.setIconUrl(url);
                EventBus.getDefault().post(loginUserEty);


            }
            break;
        }
        return false;
    }


}
